package ca.nfb.media.nfbPlayer.net
{
	import ca.nfb.media.nfbPlayer.ComModule;
	
	import flash.events.*;
	import flash.net.*;
	
	public class Remoter extends EventDispatcher
	{
		public static const KEY			:String = "ADAAS"; 
		private var connection			:NetConnection;
		private var serviceURL			:String = "http://www.nfb.ca/gwplayer/" // http://nfbtube.nfb.ca/gwplayer/";//"http://www.nfb.ca/gwplayer/"; // "http://beta.nfb.ca/gwplayer/"; //"http://nfb.tv/gwplayer/"
		
		
		
		public function Remoter(sURL:String=null):void
		{
			super();
			if (sURL != null && sURL != "")
				serviceURL = sURL;
				
			connection = new NetConnection();
			connection.addEventListener(NetStatusEvent.NET_STATUS, statusEvent, false, 0, true);
			connection.objectEncoding = ObjectEncoding.AMF0;
			trace("connection.connect to "+serviceURL);
			connection.connect(serviceURL);
		}
		
		private function statusEvent(evt:NetStatusEvent):void
		{
			trace("connected");
		}
		
		public function reEncode (encodingStr:String):void
		{
			if(encodingStr == 'AMF0')
				connection.objectEncoding = ObjectEncoding.AMF0;
			else
				connection.objectEncoding = ObjectEncoding.AMF3;
		}
		
		public function invoke(functionName:String, responder:Function, fault:Function,  ...args):void
		{
			trace("INVOKE :: "+functionName + "  ::  " + responder);
		 	//ComModule.getInstance().core.outputConsole.appendHTMLText("<br><br>INVOKING :: "+functionName + "  ::  " + responder );
		 	var appliedArgs:Array = new Array();
		 	appliedArgs.push(functionName);
			appliedArgs.push( new Responder( responder, fault ) );
			appliedArgs.push(Remoter.KEY);
			
			for(var i:int=0; i<args.length; ++i) { appliedArgs.push(args[i]); }
			connection.call.apply(connection, appliedArgs);
			
		}
		
		public function invokeWithTempKey(keyName:String, functionName:String, responder:Function, fault:Function,  ...args):void
		{
		 	//ComModule.getInstance().core.outputConsole.appendHTMLText("<br><br>INVOKING with temp key:: "+keyName+" :: "+functionName + "  ::  " + responder );
		 	var appliedArgs:Array = new Array();
		 	appliedArgs.push(functionName);
			appliedArgs.push( new Responder( responder, fault ) );
			appliedArgs.push(keyName);
			
			for(var i:int=0; i<args.length; ++i) { appliedArgs.push(args[i]); }
			connection.call.apply(connection, appliedArgs);
			
		}
	}
}